package com.tuanbiao.presenter;

import com.hzjq.data.entity.PmEntity;
import com.tuanbiao.base.mvp.BasePresenter;
import com.tuanbiao.controllers.ProjectController;
import com.tuanbiao.data.callback.OnBaseResultCallback;
import com.tuanbiao.models.ProjectModel;

import java.util.List;

import timber.log.Timber;

/**
 * @author abiao
 * @since 2022/3/25 11:58
 */
public class ProjectManagerPresenter extends BasePresenter<ProjectModel, ProjectController.View> implements ProjectController.Presenter {
    private int mPageIndex = 1;

    public ProjectManagerPresenter(ProjectModel model, ProjectController.View rootView) {
        super(model, rootView);
    }

    @Override
    public void refresh() {
        getProjectList(1);
    }

    @Override
    public void loadMore() {
        mPageIndex++;
        getProjectList(mPageIndex);
    }

    private void getProjectList(int pageIndex) {
        if(mModel == null) return;
        mModel.getProjectList(pageIndex, new OnBaseResultCallback<List<PmEntity>>() {
            @Override
            public void onSuccess(List<PmEntity> entities) {
                Timber.i("getProject#" + entities);
                if (pageIndex <= 1) mRootView.setProjects(entities);
                else mRootView.addProjects(entities);
            }

            @Override
            public void onFailed(String msg) {
                mRootView.showMessage(msg);
            }
        });
    }

    @Override
    public void updateProject(PmEntity entity) {
        mModel.refreshAuth();
        mModel.updateProject(entity, unused -> refresh());
    }

    @Override
    public void importProject(String path) {
        mModel.importPlan(path, errorResult -> {
            mRootView.showMessage(errorResult.getErrorAction());
            refresh();
            Timber.i("importProject#" + errorResult.getErrorCode());
            Timber.i("importProject#" + errorResult.getErrorAction());
        });
    }

    @Override
    public void deleteProject(PmEntity entity) {
        mModel.deleteProject(entity, unused -> refresh());
    }
}
